#!/usr/bin/env node

/**
 * 测试前端是否正确显示Excel导入的数据
 */

const { execSync } = require('child_process');
const axios = require('axios');

class FrontendDisplayTester {
  constructor() {
    this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1NzE2NDAyMCwiZXhwIjoxNzU3NzY4ODIwLCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.2pqn01o6rqlOOoOGaEPXNtwIoK-A86kPty3KWnyvY0Q';
  }

  log(message, type = 'info') {
    const timestamp = new Date().toISOString();
    const prefix = {
      'info': '🔍',
      'success': '✅',
      'error': '❌',
      'fix': '🔧'
    }[type] || 'ℹ️';
    console.log(`${prefix} [${timestamp}] ${message}`);
  }

  async checkBackendData() {
    this.log('检查后端数据');
    
    try {
      const response = await axios.get('http://localhost:3001/api/menu/public/items', {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      });
      
      const items = response.data.data.items;
      this.log(`后端返回 ${items.length} 条数据`);
      
      // 查找测试数据
      const testItems = items.filter(item => item.name.includes('1757177794265'));
      if (testItems.length > 0) {
        this.log(`后端有测试数据: ${testItems[0].name}`, 'success');
        return true;
      } else {
        this.log('后端没有测试数据', 'error');
        return false;
      }
    } catch (error) {
      this.log('后端检查失败: ' + error.message, 'error');
      return false;
    }
  }

  async testFrontendAPI() {
    this.log('测试前端API调用');
    
    try {
      // 模拟前端API调用，添加时间戳防止缓存
      const response = await axios.get('http://localhost:3001/api/menu/public/items', {
        params: { _t: Date.now() },
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      });
      
      const items = response.data.data.items;
      this.log(`前端API返回 ${items.length} 条数据`);
      
      // 查找测试数据
      const testItems = items.filter(item => item.name.includes('1757177794265'));
      if (testItems.length > 0) {
        this.log(`前端API有测试数据: ${testItems[0].name}`, 'success');
        return true;
      } else {
        this.log('前端API没有测试数据', 'error');
        return false;
      }
    } catch (error) {
      this.log('前端API测试失败: ' + error.message, 'error');
      return false;
    }
  }

  async testUIDisplay() {
    this.log('测试UI显示');
    
    try {
      const result = execSync(
        `cd /Users/andylau/Dropbox/AppDevelopment/CMB250716/admin-tests && npx playwright test --grep "检查菜单数据" --reporter=line`,
        { encoding: 'utf8', timeout: 60000 }
      );
      
      if (result.includes('1757177794265') || result.includes('测试饮料')) {
        this.log('UI显示测试通过', 'success');
        return true;
      } else {
        this.log('UI显示测试失败', 'error');
        return false;
      }
    } catch (error) {
      this.log('UI测试执行失败: ' + error.message, 'error');
      return false;
    }
  }

  async run() {
    console.log('\n' + '='.repeat(60));
    console.log('🎯 前端显示测试');
    console.log('='.repeat(60) + '\n');
    
    try {
      // 1. 检查后端数据
      const backendOK = await this.checkBackendData();
      
      // 2. 测试前端API
      const frontendAPIok = await this.testFrontendAPI();
      
      console.log('\n' + '='.repeat(60));
      if (backendOK && frontendAPIok) {
        console.log('🎉 数据链路测试成功！');
        console.log('✅ 后端数据正常，前端API正常');
        console.log('💡 如果前端界面仍不显示，可能是浏览器缓存问题');
        console.log('💡 请尝试强制刷新浏览器 (Ctrl+F5 或 Cmd+Shift+R)');
      } else {
        console.log('❌ 数据链路测试失败！');
        if (!backendOK) console.log('💡 后端数据有问题');
        if (!frontendAPIok) console.log('💡 前端API有问题');
      }
      console.log('='.repeat(60) + '\n');
      
    } catch (error) {
      console.log('\n' + '='.repeat(60));
      console.log('❌ 前端显示测试失败！');
      console.log('错误:', error.message);
      console.log('='.repeat(60) + '\n');
    }
  }
}

// 立即运行
if (require.main === module) {
  const tester = new FrontendDisplayTester();
  tester.run().catch(console.error);
}

module.exports = FrontendDisplayTester;